﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Reflection;
using Microsoft.CodeAnalysis;

namespace Generators
{
    [Generator]
    public partial class ProductVersionInfoGenerator : IIncrementalGenerator
    {
        public void Initialize(IncrementalGeneratorInitializationContext context)
        {
            IncrementalValueProvider<string?> informationalVersionProvider = context.AnalyzerConfigOptionsProvider.Select((options, _) =>
                options.GlobalOptions.TryGetValue("build_property.InformationalVersion", out string? ver) ? ver : null);

            context.RegisterSourceOutput(informationalVersionProvider, (ctx, informationalVersion) =>
            {
                // strip semver metadata (git hash) followed by + sign
                string? productVersion = informationalVersion?.Split('+')?[0];

                if (string.IsNullOrEmpty(productVersion))
                    throw new InvalidOperationException($"Unable to obtain product version at build-time.");

                // strip semver prerelease label followed by - sign for Environment.Version
                string environmentVersion = Version.Parse(productVersion.Split('-')[0]).ToString();

#if STABILIZE_PACKAGE_VERSION
                string frameworkDescriptionVersion = environmentVersion;
#else
                string frameworkDescriptionVersion = productVersion;
#endif

                ctx.AddSource("ProductVersionInfo.g.cs", $@"// <auto-generated/>

namespace System
{{
    public static partial class Environment
    {{
        /// <summary>
        /// Gets a version consisting of the major, minor, build, and revision numbers of the common language runtime.
        /// </summary>
        public static Version Version => new Version({environmentVersion.Replace(".", ", ")});
    }}
}}

namespace System.Runtime.InteropServices
{{
    public static partial class RuntimeInformation
    {{
        /// <summary>
        /// Gets the name of the .NET installation on which an app is running.
        /// </summary>
        public static string FrameworkDescription => "".NET {frameworkDescriptionVersion}"";
    }}
}}");
            });
        }
    }
}
